import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { message } from 'antd';

// 请求配置接口
export interface RequestConfig extends AxiosRequestConfig {
  skipAuth?: boolean;
  skipErrorHandler?: boolean;
}

// 响应数据接口
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

class Request {
  private instance: AxiosInstance;

  constructor() {
    // 创建axios实例
    this.instance = axios.create({
      baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:4090' : '',
      timeout: 120000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: any) => {
        // 添加认证token
        if (!config.skipAuth) {
          const token = localStorage.getItem('token');
          if (token) {
            config.headers.Authorization = `Bearer ${token}`;
          }
        }

        // 如果是 FormData，删除默认的 Content-Type，让浏览器自动设置
        if (config.data instanceof FormData) {
          delete config.headers['Content-Type'];
        }

        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        
        // 如果响应成功
        if (data.success) {
          return response;
        }
        
        console.log('asds');
        // 如果响应失败但不跳过错误处理
        if (!(response.config as any).skipErrorHandler) {
          message.error(data.error || data.message || '请求失败');
          switch (data.code) {
            case 401:
              // 未授权，清除token并跳转登录
              localStorage.removeItem('token');
              if (window.location.pathname !== '/login') {
                window.location.href = '/login';
              }
              break;
            case 403:
              message.error('权限不足');
              break;
            case 404:
              message.error('资源不存在');
              break;
            case 500:
              message.error('服务器错误');
              break;
    
          }
        }
        
        
        return Promise.reject(new Error(data.error || data.message || '请求失败'));
      },
      (error) => {
        // 处理HTTP错误
        if (error.response) {
          const { status, data } = error.response;
          
          switch (status) {
            case 401:
              // 未授权，清除token并跳转登录
              localStorage.removeItem('token');
              if (window.location.pathname !== '/login') {
                window.location.href = '/login';
              }
              break;
            case 403:
              message.error('权限不足');
              break;
            case 404:
              message.error('资源不存在');
              break;
            case 500:
              message.error('服务器错误');
              break;
            default:
              if (!error.config?.skipErrorHandler) {
                message.error(data?.error || data?.message || '网络错误');
              }
          }
        } else if (error.request) {
          message.error('网络连接失败');
        } else {
          if (!error.config?.skipErrorHandler) {
            message.error(error.message || '请求失败');
          }
        }
        
        return Promise.reject(error);
      }
    );
  }

  // GET请求
  async get<T = any>(url: string, config?: RequestConfig): Promise<T> {
    const response = await this.instance.get(url, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }

  // POST请求
  async post<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    const response = await this.instance.post(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }

  // PUT请求
  async put<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    const response = await this.instance.put(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }

  // DELETE请求
  async delete<T = any>(url: string, config?: RequestConfig): Promise<T> {
    const response = await this.instance.delete(url, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }

  // PATCH请求
  async patch<T = any>(url: string, data?: any, config?: RequestConfig): Promise<T> {
    const response = await this.instance.patch(url, data, config);
    const apiResponse: ApiResponse<T> = response.data;
    
    if (apiResponse.success) {
      return apiResponse.data as T;
    }
    
    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }

  // 上传文件
  async upload<T = any>(url: string, formData: FormData, config?: RequestConfig): Promise<T> {
    const response = await this.instance.post(url, formData, {
      ...config,
      headers: {
        // 不要手动设置 Content-Type，让浏览器自动设置 boundary
        ...config?.headers,
      },
    });
    const apiResponse: ApiResponse<T> = response.data;

    if (apiResponse.success) {
      return apiResponse.data as T;
    }

    throw new Error(apiResponse.error || apiResponse.message || '请求失败');
  }
}

// 创建请求实例
const request = new Request();

// 导出单独的方法，方便直接使用
export const get = request.get.bind(request);
export const post = request.post.bind(request);
export const put = request.put.bind(request);
export const del = request.delete.bind(request);
export const patch = request.patch.bind(request);
export const upload = request.upload.bind(request);

export default request; 